<template>
  <div class="app-container">
    <el-row class="topNum" :gutter="0">
      <el-col :span="6" class="topText topBorder">
        <h4>总设备数</h4>
        <p style="color:#2727FF">{{deviceStatus.total}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>使用中</h4>
        <p style="color:#7BAF2A">{{deviceStatus.useNum}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>空闲</h4>
        <p style="color:#27e156">{{deviceStatus.freeNum}}台</p>
      </el-col>
      <el-col :span="6" class="topText topBorder">
        <h4>离线</h4>
        <p style="color:#222222">{{deviceStatus.offLineNum}}台</p>
      </el-col>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="100px">
      <el-form-item label="充电枪名称" prop="portName">
        <el-input v-model="queryParams.portName" placeholder="请输入充电枪名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="场站名称" prop="stationId">
        <el-select v-model="queryParams.stationId" placeholder="请选择场站" clearable>
          <el-option v-for="station in stationList" :key="station.chargeStationId" :label="station.chargeStationName" :value="station.chargeStationId" />
        </el-select>
      </el-form-item>
      <el-form-item label="充电桩名称" prop="stationId">
        <el-select v-model="queryParams.deviceId" placeholder="请选择场站" clearable>
          <el-option v-for="station in pileList" :key="station.deviceId" :label="station.pileName" :value="station.deviceId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="userStatus">
        <el-select v-model="queryParams.serviceStatus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.use_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['station:port:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="portList">
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="充电枪编号" align="center" prop="id" />
      <el-table-column label="充电枪名称" align="center" prop="portName" />
      <el-table-column label="充电桩名称" align="center" prop="pileName" />
      <el-table-column label="场站名称" align="center" prop="chargeStationName" />
      <el-table-column label="电压" align="center" prop="voltage" >
        <template slot-scope="scope">{{scope.row.voltage}}V</template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="useStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.use_state" :value="scope.row.serviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['station:port:info']"
          >详情
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['station:port:edit']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['station:port:del']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getPortList" />

    <!-- 添加或修改充电枪对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="充电桩" prop="deviceId">
          <el-select :disabled="form.$tag === 'edit'" v-model="form.deviceId" placeholder="请选择充电桩" style="width: 100%">
            <el-option
              v-for="item in pileList"
              :key="item.deviceId"
              :label="item.pileName"
              :value="item.deviceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电枪编号" prop="id">
          <el-input v-model="form.id" placeholder="请输入充电枪编号" />
        </el-form-item>
        <el-form-item label="充电枪名称" prop="portName">
          <el-input v-model="form.portName" placeholder="请输入充电枪名称" />
        </el-form-item>
        <el-form-item label="电压(V)" prop="voltage">
          <el-input type="" v-model="form.voltage" placeholder="请输入电压" oninput ="value=value.replace(/[^0-9]/g,'')"/>
        </el-form-item>
        <el-form-item label="额定电流(A)" prop="current">
          <el-input type="" v-model="form.current" placeholder="请输入额定电流" oninput ="value=value.replace(/[^0-9]/g,'')"/>
        </el-form-item>
        <el-form-item label="额定电压上限(V)" prop="voltageUpperLimits">
          <el-input type="" v-model="form.voltageUpperLimits" placeholder="请输入额定电压上限" oninput ="value=value.replace(/[^0-9]/g,'')"/>
        </el-form-item>
        <el-form-item label="额定电压下限(V)" prop="voltageLowerLimits">
          <el-input type="" v-model="form.voltageLowerLimits" placeholder="请输入额定电压下限" oninput ="value=value.replace(/[^0-9]/g,'')"/>
        </el-form-item>
        <el-form-item label="额定功率(kW)" prop="power">
          <!--oninput ="value=value.replace(/^(?!0)\d+(.[0-9]{1})?$/,'')"-->
          <el-input type="" v-model="form.power" placeholder="请输入额定功率"/>
        </el-form-item>
        <el-form-item label="充电设备接口类型" prop="connectorType">
          <el-select v-model="form.connectorType" placeholder="请选择建充电设备接口类型" style="width: 100%">
            <el-option v-for="dict in dict.type.connector_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="80%" center append-to-body>
      <el-row :gutter="10">
        <el-col :span="13">
          <el-card shadow="never" style="height: 700px; border: hidden">
            <div style="text-align:center;" slot="header">
              <dict-tag style="color: green; font-weight: bold; font-size: 20px" :options="dict.type.use_state" :value="form.serviceStatus" />
            </div>
            <div style="height: 30%">
              <el-row :gutter="10">
                <el-col :span="8" style="height: auto">
                  <div style="text-align:center;">
                    <el-image style="width: 100px; height: 100px" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"/>
                    <p>充电枪模型</p>
                  </div>
                </el-col>
                <el-col :span="16">
                  <el-descriptions :labelStyle="{fontWeight: 'bold'}" style="float: right;" direction="vertical" :column="4">
                    <el-descriptions-item label="充电枪编号">{{form.id}}</el-descriptions-item>
                    <el-descriptions-item label="充电枪名称">{{form.portName}}</el-descriptions-item>
                    <el-descriptions-item label="充电桩编号">{{form.deviceId}}</el-descriptions-item>
                    <el-descriptions-item label="场站名称">{{form.chargeStationName}}</el-descriptions-item>
                    <el-descriptions-item label="电压">{{form.voltage}}V</el-descriptions-item>
                    <el-descriptions-item label="额定电流">{{form.current}}A</el-descriptions-item>
                    <el-descriptions-item label="额定电压上限">{{form.voltageUpperLimits}}V</el-descriptions-item>
                    <el-descriptions-item label="额定电压下限">{{form.voltageLowerLimits}}V</el-descriptions-item>
                    <el-descriptions-item label="额定功率">{{form.power}}kW</el-descriptions-item>
                    <el-descriptions-item label="充电设备接口类型">{{getName(form.connectorType)}}</el-descriptions-item>
                  </el-descriptions>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        <el-col :span="11">
          <el-card shadow="never" style="height: 700px; border: hidden">
            <div slot="header">
              <span style="color: darkred; font-weight: bold; font-size: 20px">充电记录</span>
              <el-date-picker
                @blur="getOrderList"
                style="float: right;"
                size="mini"
                v-model="dateArray"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
            <el-table :data="orderList" height="600px">
              <el-table-column label="开始时间" align="center" prop="startTime" />
              <el-table-column label="结束时间" align="center" prop="endTime" />
              <el-table-column label="电量" align="center" prop="totalPower" >
                <template slot-scope="scope">{{scope.row.totalPower}}kw·h</template>
              </el-table-column>
              <el-table-column label="时长" align="center" >
                <template slot-scope="scope">{{getChargeTime(scope.row)}}h</template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>

</template>

<script>
  import { queryDevice } from '@/api/iot/device'
  import { listStation } from "@/api/smart/operator/station";
  import { orderList } from "@/api/smart/custom/orderInfo";
  import { queryPile } from "@/api/smart/device/pile";
  import { getList, add, edit, del, info, getStatus } from "@/api/smart/device/port";

    export default {
      name: "port",
      dicts: ['use_state','current_type', 'connector_type'],
      data() {
        return {
          // 遮罩层
          loading: true,
          title: '',
          detailTitle: '',
          open: false,
          detailOpen: false,
          stationList: [],
          iotDeviceList: [],
          portList: [],
          pileList: [],
          orderList: [],
          deviceStatus: {
            total: 0,
            offLineNum: 0,
            freeNum: 0,
            useNum: 0
          },
          dateArray: [new Date(new Date() - 7 * 24 * 3600 * 1000), new Date()],
          // 总条数
          total: 0,
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            portName: null,
            stationId: null,
            serviceStatus: null
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
            id: [{ required: true, message: '编号不能为空', trigger: 'blur' }, {
              max: 26,
              message: '最大字符数不能超过26个字符！',
              trigger: 'blur'
            }],
            deviceId: [{ required: true, message: '充电桩编号不能为空', trigger: 'blur' }],
            portName: [{ required: true, message: '充电枪名称不能为空', trigger: 'blur' }],
            current: [{ required: true, message: '额定电流不能为空', trigger: 'blur' }],
            voltageUpperLimits: [{ required: true, message: '额定电压上限不能为空', trigger: 'blur' }],
            voltageLowerLimits: [{ required: true, message: '额定电压下限不能为空', trigger: 'blur' }],
            power: [{ required: true, message: '额定功率不能为空', trigger: 'blur' },
              {
                required: true,
                pattern: /^(?!0)\d+(.[0-9]{1})?$/,
                message: '请输入正确的额定功率(正整数/小数点后一位小数)',
                trigger: 'blur',
              }],
            connectorType: [{ required: true, message: '充电设备接口类型不能为空', trigger: 'blur' }],
          },
        }
      },
      created() {
        this.init();
        this.getPileList();
        this.getStationAndDeviceList();
      },
      methods: {
        getName(id) {
          return this.selectDictLabel(this.dict.type.connector_type,id)
        },
        init(){
          this.getPortList();
          this.getDeviceStatus();
        },
        //获取设备状态统计
        getDeviceStatus(){
          this.loading = true;
          getStatus().then(res=>{
            this.deviceStatus = res.data;
            this.loading = false;
          });
        },
        //获取充电枪列表
        getPortList(){
          this.loading = true;
          getList(this.queryParams).then(res=>{
            this.portList = res.rows;
            this.total = res.total;
            this.loading = false;
          });
        },
        //提交按钮
        submitForm(){
          let param = this.form;
          this.$refs["form"].validate(valid => {
            if(!valid) return;
            switch (this.form.$tag) {
              case "edit":
                edit(param).then(res=>{
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getPortList();
                });
                break
              case "add":
                add(param).then(res=>{
                  this.$modal.msgSuccess("添加成功");
                  this.open = false;
                  this.init();
                });
                break;
            }
          });
        },
        //详情按钮操作
        handleDetails(row){
          this.detailOpen = true;
          this.form = row;
          info(row.id).then(res=>{
            this.form = res.data;
            this.form.chargeStationName = row.chargeStationName;
            this.detailTitle = this.form.portName + '详情';
          });
          this.getOrderList();
        },
        //新增操作
        handleAdd(){
          this.form = {};
          this.form.$tag = 'add';
          this.title = "添加充电枪";
          this.open = true;
        },
        //修改操作
        handleUpdate(row) {
          this.form = Object.assign({}, row);
          this.form.$tag = 'edit';
          this.title = "修改充电枪";
          this.open = true;
        },
        //删除操作
        handleDelete(row){
          const deviceId = row.id;
          this.$modal.confirm('是否确认删除充电枪编号为"' + deviceId + '"的数据项？').then(function() {
            return del(deviceId);
          }).then(() => {
            this.init();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        },
        //获取充电记录
        getOrderList(){
          this.loading = true;
          orderList({portId: this.form.id, startDate: this.dateArray[0].toLocaleString(), endDate: this.dateArray[1].toLocaleString()}).then(res=>{
            this.orderList = res.data;
            this.loading = false;
          });
        },
        //计算充电时长
        getChargeTime(row){
          if(!row.startTime && !row.endTime){
            return '-'
          }
          let number = new Date(row.endTime).getTime() - new Date(row.startTime).getTime();
          return (number / 60 / 60 / 1000).toFixed(2);
        },
        //获取充电桩列表
        getPileList(){
          queryPile().then(res=>{
            this.pileList = res.data;
          });
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1;
          this.getPortList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.resetForm('queryForm');
          this.queryParams.deviceId = null
          this.queryParams.serviceStatus = null
          this.handleQuery();
        },
        /** 查询场站和设备列表 */
        async getStationAndDeviceList() {
          this.loading = true;
          await listStation(this.queryParams).then(response => {
            this.stationList = response.rows;
          });
          await queryDevice().then(res=>{
            this.iotDeviceList = res.data;
          });
          this.loading = false;
        },
      }
    }
</script>

<style lang="scss" scoped>
  .topNum {
    margin: 20px 0;
    h4{
      font-size: 14px;
      color: #8D8D8D;
      margin: 0 !important;
    }
    p{
      font-size: 23px;
      margin: 10px 0 0 !important;
    }
    .topText{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .topBorder{
      border-right: 1px solid #F1F1F1;
    }
  }
</style>
